import {Request} from "@/utils";
import {useAuthStore} from "@/stores";
import {router} from "@/router";

export * from '@/api/menu/index.ts'

export const request = new Request({
    baseURL: import.meta.env.VITE_API_URL,
    timeout: 5000,
    interceptorHooks: {
        requestInterceptor: (config) => {
            const authStore = useAuthStore()
            if (authStore.isLogin()) {
                config.headers.Authorization = `${authStore.tokenType} ${authStore.accessToken}`
            }
            return config;
        },
        requestInterceptorCatch: (error) => {
            return error;
        },
        responseInterceptor: (response) => {
            return response.data;
        },
        responseInterceptorCatch: (error) => {
            if (error.response?.status === 401) {
                const authStore = useAuthStore()
                window.$message?.error('登录已过期，请重新登录', {
                    closable: true,
                });
                authStore.clearToken()
                router.push({
                    path: '/login',
                })
                window.localStorage.clear()
            } else if (error.response?.status === 403) {
                window.$message?.error('权限不足', {
                    closable: true,
                });
            } else {
                window.$message?.error(error.response?.data.message ?? "服务器异常", {
                    closable: true,
                });
            }
            return error.response?.data;
        },
    },
})
